package com.labtalk.admin.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
public class JwtTokenUtil {
    private static final String CLAIM_KEY_USERID = "sub";

    private static final String CLAIM_KEY_CREATE_DATE = "create_date";

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expirationDate}")
    private Long expirationDate;

    // 根据用户id生成token
    public String generateToken(String id) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERID, id);
        claims.put(CLAIM_KEY_CREATE_DATE, new Date());
        return generateTokenByClaims(claims);
    }

    // 从token中获取用户id
    public Integer getUserIdFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        String id = claims.getSubject();
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        return Integer.parseInt(id);
    }

    // 校验token是否有效：1. token没过期；2. token中user_id与当前的操作的user_id不一致
    public boolean validateToken(String token, Integer id) {
        Integer userId = getUserIdFromToken(token);
        if (userId == null) {
            return false;
        }
        return id.equals(userId) && !isTokenExpired(token);
    }

    // token过期
    public boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        if (Objects.isNull(expiredDate)) {
            return true;
        }
        return expiredDate.before(new Date());
    }

    // 从token中获取失效时间
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        Date date = claims.getExpiration();
        if (Objects.isNull(date)) {
            return null;
        }
        return date;
    }

    // 从token中获取荷载
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            claims = e.getClaims();
        }
        return claims;
    }

    // 根据荷载生成token
    private String generateTokenByClaims(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    // 生成token失效时间 毫秒
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expirationDate * 1000);
    }
}
